package org.taohuawu.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.taohuawu.pojo.Item;
import org.taohuawu.pojo.Order;
import org.taohuawu.pojo.User;
import org.taohuawu.web.util.JsonResult;

import java.util.Arrays;
import java.util.List;

@RestController
public class RibbonController {
    @Autowired
    private RestTemplate restTemplate;

    // http://localhost:3001/item-service/35
    @GetMapping("/item-service/{orderId}")
    public JsonResult<List<Item>> getItems(@PathVariable String orderId) {
        //return restTemplate.getForObject("http://localhost:8001/item/{1}", JsonResult.class, orderId);

        //这里服务器路径用 service-id 代替，ribbon 会向服务的多台集群服务器分发请求
        return restTemplate.getForObject("http://item-service/item/{1}", JsonResult.class, orderId);
    }

    // http://localhost:3001/item-service/decreaseNumber
    @PostMapping("/item-service/decreaseNumber")
    public JsonResult decreaseNumber(@RequestBody List<Item> list) {
        return restTemplate.postForObject("http://item-service/item/decreaseNumber", list, JsonResult.class);
    }

    // http://localhost:3001/user-service/9
    @GetMapping("/user-service/{userId}")
    public JsonResult<User> getUser(@PathVariable Integer userId) {
        return restTemplate.getForObject("http://user-service/user/{1}", JsonResult.class, userId);
    }

    // http://localhost:3001/user-service/8/score?&score=99
    @GetMapping("/user-service/{userId}/score")
    public JsonResult addScore(@PathVariable Integer userId, Integer score) {
        return restTemplate.getForObject("http://user-service/user/{1}/score", JsonResult.class, score);
    }

    // http://localhost:3001/order-service/202107221156
    @GetMapping("/order-service/{orderId}")
    public JsonResult<Order> getOrder(@PathVariable String orderId) {
        return restTemplate.getForObject("http://order-service/order/{1}", JsonResult.class, orderId);
    }

    // http://localhost:3001/order-service
    @GetMapping("/order-service")
    public JsonResult addOrder() {
        return restTemplate.getForObject("http://order-service/order/", JsonResult.class);
    }
}
